using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Bots.Quest;
using Bots.Quest.QuestOrder;
using Styx;
using Styx.Common;
using Styx.CommonBot;
using Styx.CommonBot.Profiles;
using Styx.TreeSharp;
using Styx.WoWInternals.WoWObjects;
using Honorbuddy.Quest_Behaviors.ForceSetVendor;
using Action = Styx.TreeSharp.Action;


namespace Honorbuddy.Quest_Behaviors.Hooks
{
    [CustomBehaviorFileName(@"Hooks\MountHook")]
    public class MountHook : CustomForcedBehavior
    {
        public MountHook(Dictionary<string, string> args)
            : base(args)
        {

            QuestId = 0;//GetAttributeAsQuestId("QuestId", true, null) ?? 0;
            //True = hook running, false = hook stopped
            state = GetAttributeAsNullable<bool>("state", true, null, null) ?? false;

        }
        public int QuestId { get; set; }
        private bool _isBehaviorDone;


        private bool state;

        private Composite _root;

        public override bool IsDone
        {
            get
            {
                return inserted;
            }
        }

        private bool inserted = false;
        private static LocalPlayer Me
        {
            get { return (StyxWoW.Me); }
        }


        private const int ApprenticeRiding = 33388;//20
        private const int JourneyManRiding = 33391;//40
        private const int ExpertRiding = 34090;//60
        private const int ColdWeatherFlying = 54197;//68
        private const int SuperFlying = 90265;//60
        private const int FlightMastersLic = 90267;//60


        #region Trainers
        //Hellfire
        private const int HordeFlight = 35093;
        private const int AllianceFlight = 35100;

        //Stormwind
        private const int AllianceLowbie = 43769;
        //Orgimar
        private const int HordieLowbie = 44919;
        #endregion


        private static int FlightLevel
        {
            get
            {


                if (SpellManager.HasSpell(ColdWeatherFlying))
                    return 3;

                if (SpellManager.HasSpell(ExpertRiding) || SpellManager.HasSpell(SuperFlying))
                    return 2;

                if (SpellManager.HasSpell(ApprenticeRiding) || SpellManager.HasSpell(JourneyManRiding))
                    return 1;

                return 0;

            }

        }

        private static bool Hellfire
        {
            get
            {
                return StyxWoW.Me.MapId == 530;
            }
        }

        private static bool OldWorld
        {
            get
            {
                return (StyxWoW.Me.MapId == 0 || StyxWoW.Me.MapId == 1);
            }
        }

        //Return the trainer we want based on faction and location and skill.
        private static int TrainerId
        {
            get
            {
                if (OldWorld)
                {
                    return Me.IsAlliance ? AllianceLowbie : HordieLowbie;
                }
                if (Hellfire)
                {
                    return Me.IsAlliance ? AllianceFlight : HordeFlight;
                }


                return 0;
            }
        }


        public static Boolean setupQO;
        public static QuestOrder customQuestOrder;







        private static Composite QOrunner;

        private static void CleanupQuestOrder()
        {
            Logging.Write("Custom quest order complete, cleaning up.");
            TreeHooks.Instance.RemoveHook("GoobyHook2", QOrunner);
            customQuestOrder = null;

        }

        private static void SetupQuestLowbieOrder()
        {
            Logging.Write("Starting ground quest order.");
            
            //Replace with memorystream once profile is finalized    
            //var reader = new StreamReader(File.OpenRead(@"C:\Users\Dennis\Desktop\New folder\hbx\GroundTraining.XML"));
            var reader = new StreamReader(new MemoryStream(Convert.FromBase64String(GroundMounts)));
            XElement xml = XElement.Parse(reader.ReadToEnd());
            var Profile = new Profile(xml, null);
            QuestState.Instance.Order.CurrentBehavior = null;
            QuestState.Instance.Order.Nodes.InsertRange(0, Profile.QuestOrder);
            QuestState.Instance.Order.UpdateNodes();
            setupQO = true;
        }

        private static void SetupQuestFlyingOrder()
        {
            Logging.Write("Starting flying quest order.");
            //var reader = new StreamReader(File.OpenRead(@"C:\Users\Dennis\Desktop\New folder\hbx\GroundTraining.XML"));
            var reader = new StreamReader(new MemoryStream(Convert.FromBase64String(FlyingMounts)));
            XElement xml = XElement.Parse(reader.ReadToEnd());
            var Profile = new Profile(xml, null);
            QuestState.Instance.Order.CurrentBehavior = null;
            QuestState.Instance.Order.Nodes.InsertRange(0, Profile.QuestOrder);
            QuestState.Instance.Order.UpdateNodes();
            setupQO = true;


        }

        //Races that give us problems:
        //Horde
        //Blood elf -> Silvermoon
        //Undead -> Undercity
        //Alliance
        //Goats -> Goat land
        //Night elf ->Darnassus
        //Worgen -> ???


        private static Composite PurchaseMount
        {

            get
            {
                return new PrioritySelector(
                    new Decorator(r => FlightLevel == 1 && !Mount.GroundMounts.Any() && !setupQO, new Action(r => SetupQuestLowbieOrder())),
                    new Decorator(r => FlightLevel == 1 && Mount.GroundMounts.Any() && setupQO, new Action(r => setupQO = false)),
                    new Decorator(r => FlightLevel == 2 && !Mount.FlyingMounts.Any() && !setupQO, new Action(r => SetupQuestFlyingOrder())),
                    new Decorator(r => FlightLevel == 2 && Mount.FlyingMounts.Any() && setupQO, new Action(r => setupQO = false))
                    );
            }
        }

        private static void SetupTrainer()
        {
            Logging.Write(System.Windows.Media.Colors.Aquamarine, "Creating ForceTrainRiding object");
            var args = new Dictionary<string, string> { { "MobId", TrainerId.ToString() } };

            gooby = new ForceTrainRiding(args);
            gooby.OnStart();
            TreeHooks.Instance.ReplaceHook("GoobyHook", gooby.Branch);
        }

        private static void CleanUpCustomForcedBehavior()
        {

            if (gooby.GetType() == typeof(ForceTrainRiding))
            {
                Logging.Write(System.Windows.Media.Colors.Aquamarine, "Cleaningup ForceTrainRiding object");
            }
            else
            {
                Logging.Write(System.Windows.Media.Colors.Aquamarine, "Cleaningup InteractWith object");
            }

            TreeHooks.Instance.RemoveHook("GoobyHook", gooby.Branch);
            gooby.Dispose();
            gooby = null;
        }


        //Composites
        private static CustomForcedBehavior gooby = null;
        private static Composite runOtherComposite
        {
            get
            {
                return new Decorator(r => gooby != null,
                new PrioritySelector(
                    new Decorator(r => gooby.IsDone, new Action(r => CleanUpCustomForcedBehavior())),
                    new Decorator(r => !gooby.IsDone, new HookExecutor("GoobyHook"))
            ));
            }
        }

        private static Composite HellfireComposite
        {
            get
            {
                return new Decorator(r => Hellfire && Me.Level >= 60 && Me.Gold >= 268 && FlightLevel < 2, new Action(r => SetupTrainer()));

            }
        }

        private static Composite OldWordComposite
        {
            get
            {
                return new Decorator(r => OldWorld && ((Me.Level >= 20 && Me.Gold >= 5 && FlightLevel < 1) || (Me.Level >= 60 && Me.Gold >= 268 && FlightLevel < 2)), new Action(r => SetupTrainer()));

            }
        }

        public static Composite _myHook;
        public static Composite myHook
        {
            get
            {
                if (_myHook == null)
                {
                    _myHook = new Decorator(r => !Me.Combat, new PrioritySelector(runOtherComposite, PurchaseMount, OldWordComposite, HellfireComposite));
                    return _myHook;
                }
                return _myHook;
            }
            set
            {
                _myHook = value;
            }
        }

        public override void OnStart()
        {
            OnStart_HandleAttributeProblem();

            Logging.Write("MountHook:{0}  - zxbca", state);
            if (state == true)
            {
                if (_myHook == null)
                {
                    Logging.Write("MountHook:Inserting hook - zxbca");
                    TreeHooks.Instance.InsertHook("Questbot_Main", 0, myHook);
                }
                else
                {
                    Logging.Write("MountHook:Insert was requested, but was already present - zxbca");
                }


            }
            else
            {
                if (_myHook != null)
                {
                    Logging.Write("MountHook:Removing hook - zxbca");
                    TreeHooks.Instance.RemoveHook("Questbot_Main", myHook);
                    myHook = null;
                }
                else
                {
                    Logging.Write("MountHook:Remove was requested, but hook was not present - zxbca");
                }

            }

            inserted = true;

        }


        #region Profiles

        private const string GroundMounts = "[encoded data, 19476 characters]";
        private const string FlyingMounts = "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4NCjxIQlByb2ZpbGU+DQogICA8TmFtZT5NYXN0YWhnIEZseWluZyBNb3VudCBUcmFpbmluZzwvTmFtZT4NCiAgIDxNaW5MZXZlbD4xPC9NaW5MZXZlbD4NCiAgIDxNYXhMZXZlbD4xMDE8L01heExldmVsPg0KICAgPE1pbkR1cmFiaWxpdHk+MC4zPC9NaW5EdXJhYmlsaXR5Pg0KICAgPE1pbkZyZWVCYWdTbG90cz4zPC9NaW5GcmVlQmFnU2xvdHM+DQogICA8TWFpbEdyZXk+RmFsc2U8L01haWxHcmV5Pg0KICAgPE1haWxXaGl0ZT5GYWxzZTwvTWFpbFdoaXRlPg0KICAgPE1haWxHcmVlbj5UcnVlPC9NYWlsR3JlZW4+DQogICA8TWFpbEJsdWU+VHJ1ZTwvTWFpbEJsdWU+DQogICA8TWFpbFB1cnBsZT5UcnVlPC9NYWlsUHVycGxlPg0KICAgPFNlbG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